﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace DongleTest.DB
{
    public class Upload
    {
        [DllImport("wininet.dll")]
        private extern static bool InternetGetConnectedState(int Description, int ReservedValue);

        [DllImport("kernel32")]
        public static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retval, int size, string filePath);
        
        
        private static string strFilePath = Application.StartupPath + "\\Config.ini";//获取INI文件路径

        private static string serverAdd = "http://prod.icomwell.com";
        private static string port = "17000";  

        //test
        //private static string serverAdd = "http://test.icomwell.com";
        //private static string port = "13000";

        private static UrlType curType = UrlType.AppUpdate;

        private enum UrlType
        {
            /// <summary>
            /// 微信设备上传
            /// </summary>
            WxUpload,
            /// <summary>
            /// 微信设备更新
            /// </summary>
            WxUpdate,
            /// <summary>
            /// 微信设备检索二维码
            /// </summary>
            WxSearch,
            /// <summary>
            /// App设备上传
            /// </summary>
            AppUpload,
            /// <summary>
            /// 新版APP设备上传
            /// </summary>
            AppUpload2,
            /// <summary>
            /// APP设备更新
            /// </summary>
            AppUpdate,
            /// <summary>
            /// APP和微信共用设备上传
            /// </summary>
            AppWxUpload,
            /// <summary>
            /// APP和微信共用设备更新
            /// </summary>
            AppWxUpdate,
            /// <summary>
            /// APP和微信共用设备检索二维码
            /// </summary>
            AppWxSearch
        };

        private static string GetUrltoHtml(string Url, string type)
        {
            try
            {
                System.Net.WebRequest wReq = System.Net.WebRequest.Create(Url);
                // Get the response instance.
                System.Net.WebResponse wResp = wReq.GetResponse();
                System.IO.Stream respStream = wResp.GetResponseStream();

                using (System.IO.StreamReader reader = new System.IO.StreamReader(respStream, Encoding.GetEncoding(type)))
                {
                    return reader.ReadToEnd();
                }
            }
            catch (System.Exception ex)
            {
                string errorMsg = ex.Message;
            }
            return "";
        }

        //public static bool UploadTestResult(string mac, string id)
        //{
        //    string url = "http://test.icomwell.com:13000/productionDevice/integrationTestUpdate.htm?dataArr=["
        //        + @"{""macId"":""" + mac + @""",""devNum"":""" + id + @""",""integrationTestTime"":""" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + @"""}"
        //        + "]";

        //    string str = GetUrltoHtml(url, "utf-8");
        //    Regex reg = new Regex("(?<=\"code\": *)+[0-9]+(?=,)");
        //    str = reg.Match(str).Value;
        //    if (!"200".Equals(reg.Match(str).Value))
        //    {
        //        return false;
        //    }

        //    return true;
        //}

        //public static bool UploadMac(string mac)
        //{
        //    string url = "http://test.icomwell.com:13000/productionDevice/pcbaTestBatchUpdate.htm?dataArr=["
        //        + @"{""macId"":""" + mac + @""",""pcbaTestTime"":""" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + @"""}"
        //        + "]";

        //    string str = GetUrltoHtml(url, "utf-8");
        //    Regex reg = new Regex("(?<=\"code\": *)+[0-9]+(?=,)");
        //    if (!"200".Equals(reg.Match(str).Value))
        //    {
        //        return false;
        //    }
        //    return true;
        //}

        ///// <summary>
        ///// 上传sn和mac到服务器上版本2
        ///// </summary>
        ///// <param name="sn"></param>
        ///// <param name="mac"></param>
        ///// <param name="chip">芯片类型</param>
        ///// <returns></returns>
        //public static string UploadMacAndSnV2(string sn, string mac, string chip)
        //{
        //    string req = "sn=" + sn + "&macId=" + mac + "&chip=" + chip;
        //    string strRec = GetUrltoHtml(url_s_v2 + req, "utf-8");
        //    if (string.IsNullOrEmpty(strRec))
        //    {
        //        return "ERROR";
        //    }
        //    ReciveInfo jsonRec = Json.JsonToObject<ReciveInfo>(strRec);

        //    if (jsonRec.code == 200)
        //    {
        //        return "OK";
        //    }
        //    else
        //    {
        //        return jsonRec.msg;
        //    }
        //}

        ///// <summary>
        ///// 更新服务器数据
        ///// </summary>
        ///// <param name="sn"></param>
        ///// <param name="mac"></param>
        ///// <returns></returns>
        //public static string UpdateMacAndSn(string sn, string mac)
        //{
        //    string req = "macId=" + mac + "&sn=" + sn;
        //    string strRec = GetUrltoHtml(url_u + req, "utf-8");
        //    if (string.IsNullOrEmpty(strRec))
        //    {
        //        return "ERROR";
        //    }
        //    ReciveInfo jsonRec = Json.JsonToObject<ReciveInfo>(strRec);

        //    if (jsonRec.code == 200)
        //    {
        //        return "OK";
        //    }
        //    else
        //    {
        //        return jsonRec.msg;
        //    }
        //}

        ///// <summary>
        ///// 根据sn码返回对应的qrcode
        ///// </summary>
        ///// <param name="sn"></param>
        ///// <returns></returns>
        //public static string GetQrCode(string sn)
        //{
        //    string req = "sn=" + sn;
        //    string strRec = GetUrltoHtml(url_wx + req, "utf-8");
        //    if (string.IsNullOrEmpty(strRec))
        //    {
        //        return "ERROR";
        //    }
        //    ReciveInfo jsonRec = Json.JsonToObject<ReciveInfo>(strRec);

        //    if (jsonRec.code == 200)
        //    {
        //        return jsonRec.data.qrticket;
        //    }
        //    else
        //    {
        //        return jsonRec.msg;
        //    }

        //}

        ///// <summary>
        ///// 更新微信版的sn和mac对应关系
        ///// </summary>
        ///// <param name="sn"></param>
        ///// <param name="mac"></param>
        ///// <returns></returns>
        //public static string UpdateMacAndSnWx(string sn, string mac)
        //{
        //    string req = "sn=" + sn + "&macId=" + mac;
        //    string strRec = GetUrltoHtml(url_update_wx + req, "utf-8");
        //    if (string.IsNullOrEmpty(strRec))
        //    {
        //        return "ERROR";
        //    }
        //    ReciveInfo jsonRec = Json.JsonToObject<ReciveInfo>(strRec);

        //    if (jsonRec.code == 200)
        //    {
        //        return "SUCCESS";
        //    }
        //    else
        //    {
        //        return jsonRec.msg;
        //    }

        //}

        ///// <summary>
        ///// 上传sn和mac到服务器-微信版
        ///// </summary>
        ///// <param name="sn"></param>
        ///// <param name="mac"></param>
        ///// <returns></returns>
        //public static string UploadMacAndSnWx(string sn, string mac)
        //{
        //    string req = "sn=" + sn + "&macId=" + mac;
        //    string strRec = GetUrltoHtml(url_s_wx + req, "utf-8");
        //    if (string.IsNullOrEmpty(strRec))
        //    {
        //        return "ERROR";
        //    }
        //    ReciveInfo jsonRec = Json.JsonToObject<ReciveInfo>(strRec);

        //    if (jsonRec.code == 200)
        //    {
        //        return jsonRec.data.qrticket;
        //    }
        //    else
        //    {
        //        return "ERROR";
        //    }

        //}

        /// <summary>
        /// 上传信息到服务器
        /// </summary>
        /// <param name="infos">多个信息之间用逗号分隔</param>
        /// <returns></returns>
        public static string UploadInfo(string infos)
        {
            string url = serverAdd + ":" + port;
            string[] info = infos.Split(',');

            switch (curType)
            {
                case UrlType.AppUpload:
                    url += GetIniValue("Server", "AppUpload", "");
                    break;
                case UrlType.AppUpload2:
                    url += GetIniValue("Server", "AppUpload2", "");
                    break;
                case UrlType.AppUpdate:
                    url += GetIniValue("Server", "AppUpdate", "");
                    break;
                case UrlType.WxUpload:
                    url += GetIniValue("Server", "WxUpload", "");
                    break;
                case UrlType.WxUpdate:
                    url += GetIniValue("Server", "WxUpdate", "");
                    break;
                case UrlType.WxSearch:
                    url += GetIniValue("Server", "WxSearch", "");
                    break;
                case UrlType.AppWxUpload:
                    url += GetIniValue("Server", "AppWxUpload", "");
                    break;
                case UrlType.AppWxUpdate:
                    url += GetIniValue("Server", "AppWxUpdate", "");
                    break;
                case UrlType.AppWxSearch:
                    url += GetIniValue("Server", "AppWxSearch", "");
                    break;
            }

            string req = "";

            if (info.Length == 1)
            {
                req = "sn=" + info[0];
            }
            else if (info.Length == 2)
            {
                req = "sn=" + info[0] + "&macId=" + info[1];
            }
            else if (info.Length == 3)
            {
                req = "sn=" + info[0] + "&macId=" + info[1] + "&chip=" + info[2];
            }

            string strRec = GetUrltoHtml(url + req, "utf-8");
           
            if (string.IsNullOrEmpty(strRec))
            {
                return "ERROR";
            }

            ReciveInfo jsonRec = Json.JsonToObject<ReciveInfo>(strRec);

            if (jsonRec.code == 200)
            {

                if (curType == UrlType.WxSearch || curType == UrlType.AppWxSearch)
                {
                    if (jsonRec.data != null && jsonRec.data.qrticket != null)
                    {
                        return jsonRec.data.qrticket;
                    }
                }
                return "OK";
            }
            else
            {
                return jsonRec.msg;
            }

        }

        public static void SetUrlType(string mode, string function)
        {

            if (mode.Equals("A"))
            {
                if (function.Equals("T"))
                {
                    curType = UrlType.AppUpload2;
                }
                if (function.Equals("U"))
                {
                    curType = UrlType.AppUpdate;
                }
            }

            if (mode.Equals("W"))
            {
                if (function.Equals("T"))
                {
                    curType = UrlType.WxUpload;
                }
                if (function.Equals("U"))
                {
                    curType = UrlType.WxUpdate;
                }
            }


            if (mode.Equals("AW"))
            {
                if (function.Equals("T"))
                {
                    curType = UrlType.AppWxUpload;
                }
                if (function.Equals("U"))
                {
                    curType = UrlType.AppWxUpdate;
                }
            }
        }

        //public static string Upload(string sn, string mac)
        //{
        //    string req = "sn=" + sn + "&macId=" + mac;
        //    string strRec = GetUrltoHtml(url_update_wx + req, "utf-8");
        //    if (string.IsNullOrEmpty(strRec))
        //    {
        //        return "ERROR";
        //    }
        //    ReciveInfo jsonRec = Json.JsonToObject<ReciveInfo>(strRec);

        //    if (jsonRec.code == 200)
        //    {
        //        return "SUCCESS";
        //    }
        //    else
        //    {
        //        return jsonRec.msg;
        //    }
        //}

        //public static string Update(string sn, string mac)
        //{
        //    string req = "sn=" + sn + "&macId=" + mac;
        //    string strRec = GetUrltoHtml(url_update_wx + req, "utf-8");
        //    if (string.IsNullOrEmpty(strRec))
        //    {
        //        return "ERROR";
        //    }
        //    ReciveInfo jsonRec = Json.JsonToObject<ReciveInfo>(strRec);

        //    if (jsonRec.code == 200)
        //    {
        //        return "SUCCESS";
        //    }
        //    else
        //    {
        //        return jsonRec.msg;
        //    }
        //}

        //public static string Search(string sn)
        //{
        //    string req = "sn=" + sn;
        //    string strRec = GetUrltoHtml(url_wx + req, "utf-8");
        //    if (string.IsNullOrEmpty(strRec))
        //    {
        //        return "ERROR";
        //    }
        //    ReciveInfo jsonRec = Json.JsonToObject<ReciveInfo>(strRec);

        //    if (jsonRec.code == 200)
        //    {
        //        return jsonRec.data.qrticket;
        //    }
        //    else
        //    {
        //        return jsonRec.msg;
        //    }
        //}

        /// <summary>
        /// 网络是否连接
        /// </summary>
        public static bool IsConnectInternet
        {
            get { return InternetGetConnectedState(0, 0); }
        }




        /// <summary>
        /// 自定义读取INI文件中的内容方法
        /// </summary>
        /// <param name="Section">键</param>
        /// <param name="key">值</param>
        /// <returns></returns>
        public static string GetIniValue(string Section, string key, string def)
        {
            StringBuilder temp = new StringBuilder(1024);
            GetPrivateProfileString(Section, key, def, temp, 1024, strFilePath);
            return temp.ToString();
        }

    }
}
